package com.ygg.controller;

import com.ygg.result.Result;
import com.ygg.service.MsmService;
import com.ygg.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Slf4j
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/send/{phone}")
    public Result<?> send(@PathVariable String phone) {
        String code = stringRedisTemplate.opsForValue().get(phone);
        //存在验证码返回 则验证码未过期 返回ok 防止重复发送
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //不存在 则发送
        code = RandomUtil.getSixBitRandom();
//        boolean send = msmService.send(phone, code);
        boolean send = true;
        log.info(code);
        if (send) {
            stringRedisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }


    }
}
